import Icon from '@ant-design/icons';
import { ConfigProvider } from 'antd';
import { FC, useEffect, useMemo, useState } from 'react';

import { LoadState } from '../../../../types.ts';

import { Metamask, CloudSignal, Tick, NegativeEmoji } from './Icons';
import { showInsetEffect } from './insertEffect.ts';
import { useStartButtonStyles } from './styles.tsx';

interface IStartButtonProps {
    onClick: () => void;
    loadState: LoadState;
}

export const StartButton:FC<IStartButtonProps> = ({ onClick, loadState }) => {
    const { styles, cx } = useStartButtonStyles();
    const [loadingAnimation, setLoadingAnimation] = useState(false);

    useEffect(() => {
        if (loadState === 'loading') {
            setLoadingAnimation(true);
            return () => {};
        }

        if (loadState === 'connected') {
            const timeoutId = setTimeout(() => {
                setLoadingAnimation(false);
            }, 1300);

            return () => clearTimeout(timeoutId);
        }

        return  setLoadingAnimation(false);

    }, [loadState]);

    const ButtonIcon = useMemo(() => {
        if (loadState === 'loading') {
            return CloudSignal;
        }

        if (loadState === 'connected') {
            return Tick;
        }

        if (loadState === 'error') {
            return NegativeEmoji;
        }
        
        return Metamask;
    }, [loadState]);

    return (
        <ConfigProvider wave={{ showEffect: showInsetEffect }}>
            <div
                className={
                    cx(styles.button, 
                        { 
                            ['stop-animation']: !loadingAnimation,
                            ['loaded']: loadState === 'connected',
                            ['no-loaded-elements']: loadState === 'error' || loadState === 'offline',
                        },
                    )}
                onClick={onClick}
            >
                <span className={cx('gradient-ring', { ['error']: loadState === 'error' })}/>
                <span className="inner-shadow"/>
                <Icon component={ButtonIcon}/>
            </div>
        </ConfigProvider>
    );
};